package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.dao.NodeDao;
import com.lkd.entity.NodeEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.exception.LogicException;
import com.lkd.http.vo.NodeReq;
import com.lkd.service.BusinessTypeService;
import com.lkd.service.NodeService;
import com.lkd.service.RegionService;
import com.lkd.service.VendingMachineService;
import com.lkd.vo.Pager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class NodeServiceImpl  extends ServiceImpl<NodeDao, NodeEntity> implements NodeService{

    @Autowired
    private RegionService regionService;

    @Autowired
    private BusinessTypeService businessTypeService;

    @Override
    public Pager<NodeEntity> search(String name, String regionId, long pageIndex, long pageSize) {

        // 1.判断分页数据数据
        if (ObjectUtils.isEmpty(pageIndex) || pageIndex < 1) {
            pageIndex = Pager.DEFAULT_PAGE_INDEX;
        }

        if (ObjectUtils.isEmpty(pageSize) || pageSize < 1) {
            pageSize = Pager.DEFAULT_PAGE_SIZE;
        }

        // 2.创建分页对象（MP）
        Page<NodeEntity> page =  new Page<>(pageIndex,pageSize);

        // 3.构建查询对象
        LambdaQueryWrapper<NodeEntity> queryWrapper = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(name)){
            queryWrapper.like(NodeEntity::getName,name);
        }
        if(!Strings.isNullOrEmpty(regionId)){
            Long regionIdLong = Long.valueOf(regionId);
            queryWrapper.eq(NodeEntity::getRegionId,regionIdLong);
        }

        // 4.查询数据并返回
        this.page(page,queryWrapper);

        // 5.转换数据并返回 Pager对象
        return Pager.build(page);

    }

    @Autowired
    private VendingMachineService vmService;

    @Override
    public List<VendingMachineEntity> getVmList(long id) {

        LambdaQueryWrapper<VendingMachineEntity> qw = new LambdaQueryWrapper<>();

        qw.select(VendingMachineEntity::getInnerCode,
                VendingMachineEntity::getVmStatus,
                VendingMachineEntity::getLastSupplyTime);

        qw.eq(VendingMachineEntity::getNodeId,id);

        return vmService.list(qw);
    }


    /*
    * 业务分析：
    *  1.判断关键数据
    *  2.判断业务数据
    *       区域信息
    *           判断是否存在
    *       商圈信息
    *           判断是否存在
    *  3.业务操作
    *  4.返回信息
    * */
    @Override
    public boolean createNode(NodeReq nodeReq) {

        // 1.判断关键数据
        // 2.判断业务数据
        //      区域信息
        //          判断是否存在
        //      商圈信息
        //          判断是否存在
        verifyBaseNodeMsg(nodeReq);

        // 3.业务操作
        NodeEntity entity = new NodeEntity();
        BeanUtils.copyProperties(nodeReq, entity);
        entity.setRegionId(Long.valueOf(nodeReq.getRegionId()));

        var result = this.save(entity);

        // 4.返回信息
        return result;
    }

    private void verifyBaseNodeMsg(NodeReq nodeReq) {
        // 1.判断关键数据
        if (StringUtils.isEmpty(nodeReq.getName())
                || StringUtils.isEmpty(nodeReq.getAddr())
                || ObjectUtils.isEmpty(nodeReq.getCreateUserId())
                || StringUtils.isEmpty(nodeReq.getRegionId())
                || ObjectUtils.isEmpty(nodeReq.getBusinessId())
                || ObjectUtils.isEmpty(nodeReq.getOwnerId())
                || StringUtils.isEmpty(nodeReq.getOwnerName())
        ) {
            throw new LogicException("传入参数与接口不匹配");
        }

        // 2.判断业务数据

        //  区域信息
        //     判断是否存在
        var region = regionService.getById(Long.valueOf(nodeReq.getRegionId()));

        if (ObjectUtils.isEmpty(region)) {
            throw new LogicException("区域信息不存在");
        }

        //  商圈信息
        //     判断是否存在
        var businessType = businessTypeService.getById(nodeReq.getBusinessId());

        if (ObjectUtils.isEmpty(businessType)) {
            throw new LogicException("商圈信息不存在");
        }
    }

    /*
     * 业务分析：
     *  1.判断关键数据
     *  2.判断业务数据
     *       区域信息
     *           判断是否存在
     *       商圈信息
     *           判断是否存在
     *  3.业务操作
     *  4.返回信息
     * */
    @Override
    public boolean modifyNode(String nodeId, NodeReq nodeReq) {

        // 1.判断关键数据
        // 2.判断业务数据
        //      区域信息
        //          判断是否存在
        //      商圈信息
        //          判断是否存在
        if (StringUtils.isEmpty(nodeId)) {
            throw new LogicException("修改的数据id不能为空");
        }

        verifyBaseNodeMsg(nodeReq);


        // 点位信息
        //     判断是否存在
        LambdaQueryWrapper<NodeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NodeEntity::getId, nodeId);

        var count = this.count(queryWrapper);

        if (count != 1) {
            throw new LogicException("修改点位信息不存在");
        }


        // 3.业务操作
        NodeEntity nodeEntity = new NodeEntity();
        BeanUtils.copyProperties( nodeReq,nodeEntity );
        nodeEntity.setRegionId(Long.valueOf(nodeReq.getRegionId()));
        nodeEntity.setId(Long.valueOf(nodeId));

        var result = this.updateById(nodeEntity);

        // 4.返回信息
        return result;
    }


    /*
     * 业务分析：
     *  1.判断关键数据
     *  2.判断业务数据
     *       点位信息
     *           判断是否存在
     *           判断点位下是否有售货机
     *  3.业务操作
     *  4.返回信息
     * */
    @Override
    public boolean removeNodeById(Long nodeId) {

        // 1.判断关键数据
        if (ObjectUtils.isEmpty(nodeId)) {
            throw new LogicException("传入参数与接口不匹配");
        }

        // 2.判断业务数据
        //      点位信息
        //          判断是否存在
        var queryWrapper = new LambdaQueryWrapper<NodeEntity>();
        queryWrapper.eq(NodeEntity::getId, nodeId);

        var nodeCount = this.count(queryWrapper);

        if (nodeCount != 1) {
            throw new LogicException("售货机信息不存在");
        }

        //          判断点位下是否有售货机
        var vsQueryWrapper = new LambdaQueryWrapper<VendingMachineEntity>();

        vsQueryWrapper.eq(VendingMachineEntity::getNodeId, nodeId);

        var vsCount = vmService.count(vsQueryWrapper);

        if (vsCount > 0) {
            throw new LogicException("点位下有售货机无法删除");
        }

        // 3.业务操作
        var result = this.removeById(nodeId);


        // 4.返回信息
        return result;
    }


}
